#!/usr/bin/env python
"""
eBay API 使用示例

在Django项目中运行此脚本:
python manage.py shell < ebay/example_usage.py

或者在Django shell中逐步执行
"""

from ebay.services import EbayApiService
from ebay.models import Category, Product

def test_ebay_api():
    """测试eBay API功能"""
    
    print("=" * 50)
    print("eBay API 测试开始")
    print("=" * 50)
    
    # 创建服务实例
    service = EbayApiService()
    
    # 1. 测试同步类目
    print("\n1. 测试同步类目...")
    try:
        saved_count = service.sync_all_categories()
        print(f"✓ 类目同步成功，共保存 {saved_count} 个类目")
        
        # 查看类目统计
        total_categories = Category.objects.count()
        level1_count = Category.objects.filter(level=1).count()
        level2_count = Category.objects.filter(level=2).count()
        level3_count = Category.objects.filter(level=3).count()
        
        print(f"  总类目数: {total_categories}")
        print(f"  一级类目: {level1_count}")
        print(f"  二级类目: {level2_count}")
        print(f"  三级类目: {level3_count}")
        
    except Exception as e:
        print(f"✗ 类目同步失败: {e}")
    
    # 2. 测试获取类目列表
    print("\n2. 查看一级类目...")
    level1_categories = Category.objects.filter(level=1)[:5]  # 只显示前5个
    for category in level1_categories:
        print(f"  {category.category_id}: {category.category_name}")
        
        # 显示子类目
        children = category.children[:3]  # 只显示前3个子类目
        for child in children:
            print(f"    └─ {child.category_id}: {child.category_name}")
    
    # 3. 测试同步商品（选择一个类目）
    print("\n3. 测试同步商品...")
    if level1_categories.exists():
        test_category = level1_categories.first()
        print(f"选择测试类目: {test_category.category_name} ({test_category.category_id})")
        
        try:
            # 同步少量商品进行测试
            saved_count = service.sync_products_by_category(test_category.category_id, max_items=100)
            print(f"✓ 商品同步成功，共保存 {saved_count} 个商品")
            
            # 查看商品示例
            products = Product.objects.filter(category_id=test_category.category_id)[:3]
            print(f"商品示例:")
            for product in products:
                print(f"  - {product.title[:50]}...")
                print(f"    价格: {product.current_price} {product.currency}")
                print(f"    卖家: {product.seller_username}")
                
        except Exception as e:
            print(f"✗ 商品同步失败: {e}")
    
    # 4. 显示统计信息
    print("\n4. 数据库统计信息:")
    print(f"  总类目数: {Category.objects.count()}")
    print(f"  总商品数: {Product.objects.count()}")
    print(f"  有商品的类目数: {Category.objects.filter(product__isnull=False).distinct().count()}")
    
    print("\n" + "=" * 50)
    print("eBay API 测试完成")
    print("=" * 50)

def test_api_calls():
    """测试具体的API调用"""
    
    print("\n测试具体API调用...")
    service = EbayApiService()
    
    try:
        # 测试获取类目树ID
        tree_id = service.get_default_category_tree_id()
        print(f"✓ 获取类目树ID成功: {tree_id}")
        
        # 测试获取类目树（部分数据）
        tree_data = service.get_category_tree(tree_id)
        print(f"✓ 获取类目树成功，根类目数: {len(tree_data.get('rootCategoryNode', {}).get('childCategoryTreeNodes', []))}")
        
    except Exception as e:
        print(f"✗ API调用失败: {e}")

def demonstrate_queries():
    """演示数据查询功能"""
    
    print("\n演示数据查询功能...")
    
    # 查询示例
    print("1. 查找Electronics类目:")
    electronics = Category.objects.filter(category_name__icontains='Electronics').first()
    if electronics:
        print(f"   {electronics.category_name} ({electronics.category_id})")
        print(f"   层级: {electronics.level}")
        print(f"   路径: {electronics.category_path}")
        
        # 查看其商品
        products_count = Product.objects.filter(category_id=electronics.category_id).count()
        print(f"   商品数量: {products_count}")
    
    # 价格查询示例
    print("\n2. 查找价格在$100-$500之间的商品:")
    expensive_products = Product.objects.filter(
        current_price__gte=100,
        current_price__lte=500,
        currency='USD'
    )[:5]
    
    for product in expensive_products:
        print(f"   {product.title[:40]}... - ${product.current_price}")
    
    print(f"   总计: {expensive_products.count()} 个商品")

if __name__ == "__main__":
    # 运行测试
    test_ebay_api()
    test_api_calls()
    demonstrate_queries()
    
    print("\n提示: 请在Django settings.py中配置您的eBay API凭证!")
    print("详细配置请参考 ebay/settings_example.py") 